#!/bin/bash
#功能：登录失败策略

#redhat策略文件：/etc/pam.d/system-auth控制本地登录失败处理，/etc/pam.d/password-auh控制远程登录失败处理。
#Ubuntu策略文件：/etc/pam.d/login控制本地登录失败处理，/etc/pam.d/common-auth控制远程登录失败处理
#auth required pam_tally2.so 
#deny=5  
#unlock_time=600 
#even_deny_root 
#root_unlock_time=600



LOGIN_CONF='auth required pam_tally2.so deny=5 unlock_time=600 even_deny_root root_unlock_time=600'
###################################################################################
#SH
SHPATH=`readlink -f $0`
SHDIR=`dirname $SHPATH`
SHNAME="$0"

#DIR
LOG_DIR=$SHDIR/logs/$SHNAME
TMP_DIR=$SHDIR/temp/$SHNAME
mkdir -p $LOG_DIR $TMP_DIR

FILE_NAME='system-auth password-auh login common-auth'





#
for i in `echo $FILE_NAME`
do

	FILE_PATH=`find /etc/pam.d -type f -name "${i}" | grep -v init.bak`
	for ii in `echo $FILE_PATH`
	do
		if [ ! -f "$ii.init.bak" ];then cp $ii $ii.init.bak;fi
		LINE_NUM=`cat -n $ii |awk '$2=="auth" {print}'|awk '$3=="required" {print}'|awk '$4=="pam_tally2.so" {print}'|awk '{print $1}'`
		if [ -z "$LINE_NUM" ];then
			echo "$LOGIN_CONF" >> $ii
			if [ $? -eq 0 ];then echo "Success,FILE=${ii} 添加登录鉴权: $LOGIN_CONF 成功。";else echo "Error!FILE=${ii} 添加登录鉴权${LOGIN_CONF}失败！请检测文件权限，或使用root用户重试！";fi
		else
			for iii in `echo $LINE_NUM`
			do
				DIFF_VAR=`sed -n ${iii}p $ii|sed  's/auth//g' |sed  's/required//g' |sed  's/pam_tally2.so//g' |sed 's/even_deny_root//g' |sed 's/root_unlock_time=600//g'|sed  's/deny=5//g' |sed 's/unlock_time=600//g'|tr -d ' '` 
				if [ -z "$DIFF_VAR" ];then
					echo "Tip,FILE=${ii} 鉴权已存在 ${LOGIN_CONF}，跳过添加。"
				else 
					sed -i "$iii s/^/#/" $ii
					sed -i "N;${iii}a $LOGIN_CONF" $ii
					if [ $? -eq 0 ];then echo "Success,FILE=${ii} 添加登录鉴权: $LOGIN_CONF 成功。";else echo "Error!FILE=${ii} 添加登录鉴权${LOGIN_CONF}失败！请检测文件权限，或使用root用户重试！";fi
				fi
			done
		fi
	done

done


